<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="登录"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="formRules.code"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import { login } from "@/api/login";
export default {
  name: "Login",
  data() {
    return {
      // 手机号和验证码
      user: {
        mobile: "17090086870",
        code: "246810",
      },
      // 表单校验规则
      formRules: {
        mobile: [
          { required: true, message: "请输入手机号" },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: "手机号格式错误" },
        ],
        code: [
          { required: true, message: "请输入验证码" },
          { pattern: /^\d{6}$/, message: "验证码格式错误" },
        ],
      },
    };
  },
  created() {},
  methods: {
    //   登录
    async onSubmit() {
      this.$toast.loading({
        message: "登录中...",
        forbidClick: true,
        duration: 0,
      });
      try {
        const { data } = await login(this.user);
        this.$store.commit("setUser", data.data);
        this.$toast.success("登录成功");
      } catch (e) {
        this.$toast.fail("登录失败，手机号或验证码错误");
      }
    },
  },
};
</script>
<style scoped>
.van-form {
  margin-top: 20px;
  width: 90%;
  margin-left: 5%;
}
</style>
